package com.yoomiito.app.share.ui;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.os.Build;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestBuilder;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.google.zxing.WriterException;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.yoomiito.app.Constant;
import com.yoomiito.app.R;
import com.yoomiito.app.adapter.my.InviteFriendAdAdapter;
import com.yoomiito.app.base.App;
import com.yoomiito.app.base.BaseActivity;
import com.yoomiito.app.model.bean.UserInfo;
import com.yoomiito.app.model.config.ConfigInfo;
import com.yoomiito.app.model.my.InviteFriend;
import com.yoomiito.app.share.presenter.InviteSharePresenter;
import com.yoomiito.app.utils.AllUtils;
import com.yoomiito.app.utils.DensityUtil;
import com.yoomiito.app.utils.ImageLoader;
import com.yoomiito.app.utils.ImageUtils;
import com.yoomiito.app.utils.L;
import com.yoomiito.app.utils.ResUtil;
import com.yoomiito.app.utils.UserInfoConfig;
import com.yoomiito.app.utils.YMToast;
import com.yoomiito.app.utils.ZxingUtil;
import com.yoomiito.app.utils.wx.UMengShareUtils;
import com.yoomiito.app.widget.SpacingDecoration;
import com.yoomiito.app.widget.dialog.CustomDialog1;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

@Deprecated
public class InviteShareActivity extends BaseActivity<InviteSharePresenter> {

    @BindView(R.id.tv_center)
    TextView mTitleView;
    @BindView(R.id.ad_view)
    ImageView mShowADView;
    @BindView(R.id.rcy)
    RecyclerView mRecyclerView;

    LinearLayout mContainerInviteCode;
    View mAdView;
    ImageView mErWeiMaIv;
    LinearLayout mAdIv;

    private String inviteCode;
    private Bitmap mBitmap;
    private ImageView mUserPhoto;
    private TextView mUserName;
    private InviteFriendAdAdapter friendAdAdapter;
    private CustomDialog1 mCustomDialog;

    @Override
    public int getLayoutId() {
        return R.layout.act_my_invite_friend;
    }

    @Override
    public InviteSharePresenter newP() {
        return new InviteSharePresenter(App.mAppConfig);
    }

    public static void start(Context context, String inviteCode) {
        Intent intent = new Intent(context, InviteShareActivity.class);
        intent.putExtra(Constant.INVITE_CODE, inviteCode);
        context.startActivity(intent);
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        mTitleView.setText("邀请好友");
        mTitleView.setVisibility(View.VISIBLE);
        inviteCode = getIntent().getStringExtra(Constant.INVITE_CODE);

        initView();
        initAd();
        showLoading();
        getP().getInviteADData();
    }

    private void initAd() {
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this, RecyclerView.HORIZONTAL, false));
        mRecyclerView.addItemDecoration(new SpacingDecoration(DensityUtil.dp2px(6), 0, false));
        friendAdAdapter = new InviteFriendAdAdapter(null);
        mRecyclerView.setAdapter(friendAdAdapter);
        friendAdAdapter.setOnItemClickListener((adapter, view, position) -> {
                    makeCodeView(friendAdAdapter.getData().get(position).getColor());
                    InviteFriend.InviteFriendInfo info = friendAdAdapter.getData().get(position);
                    makeThemeAd(info.getImg_url(), info.getDefaultResource());
                }
        );
    }

    private void initView() {
        mAdView = LayoutInflater.from(this).inflate(R.layout.item_invite_friend_1, null, false);
        mAdIv = mAdView.findViewById(R.id.ad_iv);
        mUserPhoto = mAdView.findViewById(R.id.user_photo);
        mUserName = mAdView.findViewById(R.id.user_name);
        mContainerInviteCode = mAdView.findViewById(R.id.invite_friend_invite_code);
        mErWeiMaIv = mAdView.findViewById(R.id.invite_friend_erweima);

        UserInfo userInfo = UserInfoConfig.getUser();
        mUserName.setText(userInfo.getName());
        ImageLoader.getInstance().into(this, userInfo.getHeadimgurl(), mUserPhoto);
        makeErWeiMa();
    }

    private void makeErWeiMa() {
        ConfigInfo configInfo = UserInfoConfig.getConfigInfo();
        try {
            mErWeiMaIv.setImageBitmap(ZxingUtil.cretaeZxing(configInfo.getInvite_url().getValue(), getResources().getColor(R.color.color_black)));
        } catch (WriterException e) {
            e.printStackTrace();
        }
    }

    private void makeThemeAd(String url, int defaultResource) {
        RequestBuilder builder;
        if (defaultResource == 0) {
            builder = Glide.with(this).asBitmap().load(url);
        } else {
            builder = Glide.with(this).asBitmap().load(defaultResource);
        }
        builder.into(new SimpleTarget<Bitmap>() {
            @Override
            public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                mAdIv.setBackground(ImageUtils.bitmapToDrawable(resource));
                mBitmap = ImageUtils.viewSaveToImage(mAdView);
                mShowADView.setImageBitmap(mBitmap);
            }
        });
    }

    public void setData(InviteFriend inviteFriend) {
        if (inviteFriend == null || inviteFriend.getData() == null || inviteFriend.getData().size() == 0) {
            inviteFriend = new InviteFriend();
            List<InviteFriend.InviteFriendInfo> infos = new ArrayList();
            InviteFriend.InviteFriendInfo info = new InviteFriend.InviteFriendInfo();
            info.setColor("#ef3a11");
            info.setDefaultResource(R.drawable.default_invite_friend);
            info.setTitle("海量优惠券");
            infos.add(info);
            inviteFriend.setData(infos);
        }
        friendAdAdapter.setNewData(inviteFriend.getData());
        makeCodeView(inviteFriend.getData().get(0).getColor());
        ImageUtils.layoutView(mAdView, DensityUtil.dp2px(375), DensityUtil.dp2px(667));
        makeThemeAd(inviteFriend.getData().get(0).getImg_url(), inviteFriend.getData().get(0).getDefaultResource());
    }


    @OnClick({R.id.iv_back_left, R.id.act_my_invite_friend_download, R.id.act_my_invite_friend_share_wx, R.id.act_my_invite_friend_share_wx_circle})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back_left:
                finish();
                break;
            case R.id.act_my_invite_friend_download:
                if (AllUtils.isFastClick()) {
                    return;
                }
                if (mBitmap == null) {
                    mBitmap = ImageUtils.getViewBitmap(mAdView);
                }
                if (Build.VERSION.SDK_INT >= 23) {
                    requestPermission();
                } else {
                    loadPic();
                }
                break;
            case R.id.act_my_invite_friend_share_wx:
                if (AllUtils.isFastClick()) {
                    return;
                }
                if (mBitmap == null) {
                    mBitmap = ImageUtils.getViewBitmap(mAdView);
                }
                UMengShareUtils.shareWXPic(SHARE_MEDIA.WEIXIN, this, mBitmap);
                break;
            case R.id.act_my_invite_friend_share_wx_circle:
                if (AllUtils.isFastClick()) {
                    return;
                }
                if (mBitmap == null) {
                    mBitmap = ImageUtils.getViewBitmap(mAdView);
                }
                UMengShareUtils.shareWXPic(SHARE_MEDIA.WEIXIN_CIRCLE, this, mBitmap);
                break;
        }
    }

    //把邀请码添加到布局上
    private void makeCodeView(String color) {
        if (!color.startsWith("#")) {
            color = "#" + color;
        }
        L.i("color: " + color);
        if (mContainerInviteCode.getChildCount() == 0) {
            initCodeView(color);
        } else {
            setBgColorForInviteCode(color);//5d51f0  2849f2  f75735 ef3a11
        }
    }

    private void setBgColorForInviteCode(String color) {
        int size = mContainerInviteCode.getChildCount();
        for (int i = 0; i < size; i++) {
            View view = mContainerInviteCode.getChildAt(i);
            if (view instanceof TextView) {
                TextView tv = (TextView) view;
                GradientDrawable drawable = (GradientDrawable) tv.getBackground();
                drawable.setColor(Color.parseColor(color));
            }
        }
    }

    private void initCodeView(String color) {
        char[] code = inviteCode.toCharArray();
        LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) mContainerInviteCode.getLayoutParams();
        int parentWidth = lp.width;
        int div = DensityUtil.dp2px(2);
        int width = (parentWidth - (code.length - 1) * div) / code.length;
        for (int i = 0; i < code.length; i++) {
            TextView tv = new TextView(this);
            LinearLayout.LayoutParams tvLp = new LinearLayout.LayoutParams(width, width);
            tv.setGravity(Gravity.CENTER);
            tv.setTextColor(ResUtil.getColor(R.color.color_white));
            tv.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 30);
            tv.setBackgroundResource(R.drawable.bg_invite_code_3);
            GradientDrawable drawable = (GradientDrawable) tv.getBackground();
            drawable.setColor(Color.parseColor(color));
            tv.setTypeface(AllUtils.getTypeface());
            tv.setText(String.valueOf(code[i]));
            tv.setLayoutParams(tvLp);
            mContainerInviteCode.addView(tv);
            if (i != 0 || i != code.length - 1) {
                View line = new View(this);
                LinearLayout.LayoutParams viewLp = new LinearLayout.LayoutParams(div, 0);
                line.setLayoutParams(viewLp);
                mContainerInviteCode.addView(line);
            }
        }
    }

    public void requestPermission() {
        final String[] permissions = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
        StringBuilder sb = null;
        for (String permission : permissions) {
            if (ActivityCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                if (sb == null) {
                    sb = new StringBuilder();
                }
                String str = AllUtils.permissionTipMap(permission);
                if (sb.indexOf(str) == -1) {
                    if (!TextUtils.isEmpty(sb)) {
                        sb.append("\n\n");
                    }
                    sb.append(str);
                }
            }
        }
        if (sb == null || TextUtils.isEmpty(sb)) {
            AllUtils.requestPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE,
                            Manifest.permission.READ_EXTERNAL_STORAGE)
                    .subscribe(aBoolean -> {
                        if (aBoolean) loadPic();
                    });
        } else {
            if (mCustomDialog == null) {
                mCustomDialog = new CustomDialog1(this, () -> {
                    AllUtils.requestPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE,
                                    Manifest.permission.READ_EXTERNAL_STORAGE)
                            .subscribe(aBoolean -> {
                                if (aBoolean) loadPic();
                            });
                });
            }
            mCustomDialog.setContent(String.valueOf(sb));
            mCustomDialog.show();
        }


    }

    private void loadPic() {
        ImageLoader.getInstance().downloadPic(this, mBitmap);
        Toast.makeText(context, "保存成功", Toast.LENGTH_SHORT).show();
    }

}
